package ru.sanluck.tg.bot;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.api.objects.User;
import ru.sanluck.BookshelfTgConfiguration;
import ru.sanluck.tg.TgUser;
import ru.sanluck.tg.TgUserService;
import ru.sanluck.tg.command.TgCommand;

import java.util.List;

@Component
@Slf4j
public class BookshelfBot extends TelegramLongPollingBot {

    private final BookshelfTgConfiguration tgConfiguration;
    private final TgUserService tgUserService;
    private final List<TgCommand> commands;


    public BookshelfBot(BookshelfTgConfiguration tgConfiguration,
                        TgUserService tgUserService,
                        List<TgCommand> commands) {
        super(tgConfiguration.getBotToken());
        this.tgConfiguration = tgConfiguration;
        this.tgUserService = tgUserService;
        this.commands = commands;
    }

    @Override
    public void onUpdateReceived(Update update) {
        if (update.hasMessage() && (update.getMessage().isCommand() || update.getMessage().isUserMessage())) {
            String messageText = update.getMessage().getText();
            User user = update.getMessage().getFrom();
            TgUser tgUser = tgUserService.getUser(user.getUserName());
            commands.stream()
                    .filter(tgCommand -> checkCommand(tgCommand, messageText, tgUser))
                    .findAny()
                    .ifPresent(tgCommand -> tgCommand.executeCommand(update.getMessage(), BookshelfBot.this));
        }
    }

    private boolean checkCommand(TgCommand tgCommand, String messageText, TgUser user) {
        if (user == null) {
            return tgCommand.commandText().equals(messageText);
        }
        return tgCommand.commandText().equals(messageText) || tgCommand.dialogs().contains(user.getDialog());
    }

    @Override
    public String getBotUsername() {
        return tgConfiguration.getBotName();
    }
}
